﻿using System;
using UnityEngine;

public class MapItem : MonoBehaviour
{
    public int X;
    public int Y;
    private MapItemState state;
    private MapItemSelectedState selectedState;
    private MeshRenderer render;

    public MapItemState State
    {
        get { return state; }
        set
        {
            state = value;
            ChangeColorAction();
        }
    }

    public MapItemSelectedState SelectedState
    {
        get { return selectedState; }
        set
        {
            selectedState = value;
            ChangeColorAction();
        }
    }

    public static Action ResetSelectedStateAction;
    public static Action ChangeColorAction;
    public static Action PlaceAction; 

    // Use this for initialization
    void Start()
    {
        state = MapItemState.Free;
        selectedState = MapItemSelectedState.None;
        render = GetComponent<MeshRenderer>();
        ResetSelectedStateAction += ResetState;
        ChangeColorAction += ChangeDefaultColor;
        PlaceAction += Place;
    }

    private void OnDestroy()
    {
        ResetSelectedStateAction -= ResetState;
        ChangeColorAction -= ChangeDefaultColor;
        PlaceAction -= Place;
    }



    void ChangeDefaultColor()
    {
        Color temp = Color.white;
        switch (state)
        {
            case MapItemState.Free:
                temp = new Color32(255, 218, 152, 255);
                break;
            case MapItemState.Placed:
                temp = Color.cyan;
                break;
        }

        switch (selectedState)
        {
            case MapItemSelectedState.ValidSelected:
                temp = Color.green;
                break;
            case MapItemSelectedState.InvalidSelected:
                temp = Color.red;
                break;
        }
        render.material.color = temp;
    }

    private void ResetState()
    {
        selectedState = MapItemSelectedState.None;
        ChangeDefaultColor();
    }

    private void Place()
    {
        if (selectedState == MapItemSelectedState.ValidSelected)
        {
            state = MapItemState.Placed;
            render.material.color = Color.cyan;
        }
    }
}

public enum MapItemState
{
    Free,
    Placed
}

public enum MapItemSelectedState
{
    None,
    ValidSelected,
    InvalidSelected,
}
